<template>
  <div class="exam-container">
    <!-- 警告提示已移除 -->
    
    <!-- 考试信息区域 -->
    <div class="exam-header">
      <div class="exam-info">
        <h2>{{ examInfo.name }}</h2>
        <div class="info-items">
          <span>总分：{{ examInfo.totalScore }}分</span>
          <span>时长：{{ examInfo.duration }}分钟</span>
          <span>题目数：{{ examInfo.questionCount }}题</span>
        </div>
      </div>
      <div class="countdown">
        剩余时间：{{ formatTime(remainingTime) }}
      </div>
    </div>

    <div class="exam-content">
      <!-- 题目区域 -->
      <div class="question-area">
        <div v-for="(question, index) in questions" :key="question.id" class="question-item">
          <div class="question-header">
            <span class="question-number">第{{ index + 1 }}题</span>
            <span class="question-type">{{ getQuestionTypeName(question.type) }}</span>
            <span class="question-score">({{ question.score }}分)</span>
          </div>
          <div class="question-content">{{ question.content }}</div>
          
          <!-- 选择题选项 -->
          <div v-if="question.type === 1 || question.type === 2" class="options">
            <el-radio-group v-if="question.type === 1" v-model="answers[question.id]">
              <el-radio 
                v-for="option in question.options" 
                :key="option.key" 
                :label="option.key"
              >
                {{ option.key }}. {{ option.content }}
              </el-radio>
            </el-radio-group>
            
            <el-checkbox-group v-if="question.type === 2" v-model="answers[question.id]">
              <el-checkbox 
                v-for="option in question.options" 
                :key="option.key" 
                :label="option.key"
              >
                {{ option.key }}. {{ option.content }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
          <!-- 判断题选项 -->
          <div v-if="question.type === 3" class="options">
            <el-radio-group v-model="answers[question.id]">
              <el-radio :value="1">正确</el-radio>
              <el-radio :value="0">错误</el-radio>
            </el-radio-group>
          </div>
          
          <!-- 填空题答案 -->
          <div v-if="question.type === 4" class="fill-blank">
            <el-input 
              v-model="answers[question.id]"
              type="textarea"
              placeholder="请输入答案"
            ></el-input>
          </div>
          
          <!-- 主观题答案 -->
          <div v-if="question.type === 5" class="subjective">
            <el-input 
              v-model="answers[question.id]"
              type="textarea"
              :rows="4"
              placeholder="请输入答案"
            ></el-input>
          </div>
        </div>
      </div>
      
      <!-- 答题卡 -->
      <div class="question-card">
        <div class="card-header">答题卡</div>
        <div class="card-content">
          <div 
            v-for="(question, index) in questions" 
            :key="question.id"
            class="card-item"
            :class="{ 
              'answered': isQuestionAnswered(question.id),
              'current': currentQuestionIndex === index 
            }"
            @click="scrollToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-container">
      <el-button 
        type="primary" 
        size="large" 
        :loading="submitting"
        @click="handleSubmit"
      >
        提交试卷33
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import examApi from '@/api/exam'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 考试信息
const examInfo = ref({
  name: '示例考试',
  totalScore: 100,
  duration: 120,
  questionCount: 0
})

// 题目列表
const questions = ref([])
// 答案对象
const answers = ref({})
// 剩余时间（秒）
const remainingTime = ref(0)
// 当前题目索引
const currentQuestionIndex = ref(0)
// 定时器
let timer = null
// 提交状态
const submitting = ref(false)

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) {
    return '00:00:00'
  }
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 获取题目类型编号
const getQuestionType = (typeStr) => {
  const types = {
    '单选题': 1,
    '多选题': 2,
    '判断题': 3,
    '填空题': 4,
    '问答题': 5
  }
  return types[typeStr] || 1
}

// 获取题目类型名称
const getQuestionTypeName = (type) => {
  const types = {
    1: '单选题',
    2: '多选题',
    3: '判断题',
    4: '填空题',
    5: '问答题'
  }
  return types[type] || '未知类型'
}

// 判断题目是否已答
const isQuestionAnswered = (questionId) => {
  const answer = answers.value[questionId]
  if (Array.isArray(answer)) {
    return answer.length > 0
  }
  return answer !== undefined && answer !== ''
}

// 滚动到指定题目
const scrollToQuestion = (index) => {
  currentQuestionIndex.value = index
  const questionElements = document.querySelectorAll('.question-item')
  if (questionElements[index]) {
    questionElements[index].scrollIntoView({ behavior: 'smooth' })
  }
}

// 检查未答题目
const checkUnansweredQuestions = () => {
  const unanswered = questions.value.filter(q => !isQuestionAnswered(q.id))
  return unanswered.length > 0 ? unanswered.map(q => questions.value.indexOf(q) + 1) : []
}

// 提交试卷
const handleSubmit = async () => {
  if (submitting.value) return
  
  try {
    submitting.value = true
    
    const unanswered = checkUnansweredQuestions()
    if (unanswered.length > 0) {
      try {
        await ElMessageBox.confirm(
          `第 ${unanswered.join(', ')} 题尚未作答，确定要提交吗？`,
          '提示',
          {
            confirmButtonText: '确定提交',
            cancelButtonText: '继续作答',
            type: 'warning'
          }
        )
      } catch {
        submitting.value = false
        return
      }
    }

    // 构造提交数据
    const submitAnswers = questions.value.map(q => {
      let answer = answers.value[q.id]
      // 如果是多选题，将数组转换为逗号分隔的字符串
      if (q.type === 2 && Array.isArray(answer)) {
        answer = answer.join(',')
      }
      
      // 格式化时间为后端需要的格式 (yyyy-MM-dd'T'HH:mm:ss.SSS)
      const now = dayjs()
      const formattedTime = now.format('YYYY-MM-DD[T]HH:mm:ss.SSS')
      
      return {
        questionId: q.id,
        questionType: getQuestionTypeName(q.type),
        studentAnswer: answer || '',
        submitTime: formattedTime
      }
    })

    const submitData = {
      examId: parseInt(route.query.examId),
      schoolNumber: JSON.parse(sessionStorage.getItem('userInfo')).schoolNumber,
      answers: submitAnswers
    }

    // 调用提交接口
    const res = await examApi.submitAnswer(submitData)
    
    if (res.code === 200) {
      ElMessage.success('提交成功！')
      router.push('/student/exam-list')
    } else {
      ElMessage.error(res.message || '提交失败，请重试')
    }
  } catch (error) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 自动提交
const autoSubmit = () => {
  ElMessage.warning('考试时间已到，系统将自动提交试卷')
  handleSubmit()
}

// 获取考试信息和题目
const loadExamData = async () => {
  try {
    const examId = route.query.examId
    if (!examId) {
      ElMessage.error('考试ID不能为空')
      router.push('/student/exam-list')
      return
    }

    // 获取考试信息和题目
    const response = await examApi.getExamQuestion(examId)
    const examData = response.data
    
    // 设置考试基本信息
    examInfo.value = {
      name: examData.examName,
      totalScore: examData.totalScore,
      duration: examData.duration,
      questionCount: examData.questions.length
    }
    
    // 计算剩余时间（秒）
    const startTime = dayjs(examData.startTime) // 考试开始时间
    const now = dayjs() // 当前时间
    const elapsedSeconds = now.diff(startTime, 'second') // 已经过去的秒数
    const remainingSeconds = (examData.duration * 60) - elapsedSeconds // 剩余秒数
    
    // 如果剩余时间小于等于0，说明考试时间已到
    if (remainingSeconds <= 0) {
      ElMessage.warning('考试时间已结束')
      router.push('/student/exam-list')
      return
    }
    
    // 设置剩余时间（秒）
    remainingTime.value = remainingSeconds
    
    // 处理题目数据
    questions.value = examData.questions.map(q => ({
      id: q.questionId,
      type: getQuestionType(q.type),
      content: q.content,
      score: q.score,
      orderNum: q.orderNum,
      options: q.options ? q.options.map(opt => ({
        key: opt.label,
        content: opt.content
      })) : null
    }))
    
    // 初始化答案对象
    const initialAnswers = {}
    questions.value.forEach(q => {
      initialAnswers[q.id] = q.type === 2 ? [] : ''
    })
    answers.value = initialAnswers
    
    // 启动倒计时
    timer = setInterval(() => {
      if (remainingTime.value > 0) {
        remainingTime.value--
      } else {
        clearInterval(timer)
        autoSubmit()
      }
    }, 1000)
    
  } catch (error) {
    console.error('加载考试数据失败:', error)
    ElMessage.error('加载考试数据失败：' + error.message)
    router.push('/student/exam-list')
  }
}

onMounted(() => {
  if (!route.query.examId) {
    ElMessage.error('考试ID不能为空')
    router.push('/student/exam-list')
    return
  }
  loadExamData()
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.exam-container {
  padding: 20px;
  height: 100%;
  position: relative;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.exam-info h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.info-items {
  display: flex;
  gap: 20px;
  color: #606266;
}

.countdown {
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.exam-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 180px);
}

.question-area {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
}

.question-item {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.question-header {
  margin-bottom: 15px;
}

.question-number {
  font-weight: bold;
  color: #303133;
  margin-right: 10px;
}

.question-type {
  color: #409EFF;
  margin-right: 10px;
}

.question-score {
  color: #F56C6C;
}

.question-content {
  margin-bottom: 15px;
  color: #303133;
  line-height: 1.6;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.fill-blank, .subjective {
  margin-top: 10px;
}

.question-card {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.card-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  flex: 1;
  overflow-y: auto;
}

.card-item {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.card-item:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.card-item.answered {
  background: #409EFF;
  color: #090909;
  border-color: #409EFF;
}

.card-item.current {
  border-color: #409EFF;
  color: #090909;
}

.submit-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 20px;
  display: flex;
  justify-content: center;
  z-index: 1000;
}

.submit-container .el-button {
  width: 200px;
  height: 45px;
  font-size: 16px;
  border-radius: 23px;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-radio), :deep(.el-checkbox) {
  margin-right: 0;
  margin-bottom: 10px;
  width: 100%;
}

:deep(.el-radio__label), :deep(.el-checkbox__label) {
  white-space: normal;
}
</style>

